package sh.dao.plugin;

import sh.dto.Measurements;
import sh.orm.convert.AbstractTypeConvertor;
import sh.orm.convert.JdbcType;
import sh.orm.convert.MappedTypes;
import sh.util.BizException;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 三围类型转换器
 * @author lqq
 * @date 2019/2/28
 */
@MappedTypes(returnType = Measurements.class, jdbcType = JdbcType.VARCHAR)
public class MeasurementsTypeConvertor extends AbstractTypeConvertor<Measurements> {

    private final String DOUHAO = ",";

    /** 正确的三围数组是3个 */
    private final int MEASUREMENTS_LENGTH = 3;

    @Override
    public String convertToJdbcValue(Measurements javaObj) {
        StringBuilder sb = new StringBuilder();
        sb.append(javaObj.getBust()).append(DOUHAO);
        sb.append(javaObj.getWaist()).append(DOUHAO);
        sb.append(javaObj.getHip());
        return sb.toString();
    }

    @Override
    public Measurements convertToJavaType(String columnName, ResultSet rs) {
        try {
            String s = rs.getString(columnName);
            if(s == null){
                return null;
            }
            String[] measurementsArr = s.split(DOUHAO);

            if(measurementsArr.length != MEASUREMENTS_LENGTH){
                throw new BizException("三围数据存储异常" + s);
            }
            Measurements measurements = new Measurements();
            measurements.setBust(Float.valueOf(measurementsArr[0]));
            measurements.setWaist(Float.valueOf(measurementsArr[1]));
            measurements.setHip(Float.valueOf(measurementsArr[2]));
            return measurements;

        } catch (SQLException e) {
            e.printStackTrace();
            throw new BizException("操作resultSet异常" + e.getMessage());
        }
    }


}
